const express = require('express');
const path = require('path');
const fs = require('fs');
const formidable = require('formidable');
const bodyParser = require('body-parser');
const dbsql = require('./config/mysqlConfig.js');
const log4js = require('./config/logConfig.js');
const TopClient = require('./taobao/index.js').ApiClient;
const loggers = log4js.logger('q', 'trace');
let OSS = require('ali-oss');
var AipSpeechClient = require("./baidu-sdk/src/index.js").speech;

// 设置APPID/AK/SK
var APP_ID = "15640353";
var API_KEY = "IkISgDb78UiginF6xr0nlw8B";
var SECRET_KEY = "r97DwGpCG5kN9Mdl1onPOXpEvpdKwy7x";

// 新建一个对象，建议只保存一个对象调用服务接口
var clientbaidu = new AipSpeechClient(APP_ID, API_KEY, SECRET_KEY);

let OSSclient = new OSS({
  region: 'oss-cn-beijing',
  //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
  accessKeyId: 'LTAIyDvaFFYsVngZ',
  accessKeySecret: 'swTElew3782hrtZ8zMtb66yLW04pPS',
  bucket: 'laoniu-tou',
});
dbsql.connect();

const app = express();
app.use(bodyParser.urlencoded({extended: true}));
//配置请求头
app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  res.header('X-Powered-By', ' 3.2.1');
  res.header('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
  next();
});

var client = new TopClient({
  'appkey': '25430603',
  'appsecret': 'fb5dc79514832573b070fd6c934b366e',
  'REST_URL': 'http://gw.api.taobao.com/router/rest',
});

log4js.use(app);
app.listen(5041);
console.log('http://localhost:' + 5041);

//根据手机号查询像个人信息
function inquiryinfo(phone) {
  return 'SELECT * FROM appunion.`userInfo` WHERE phone=\'' + phone + '\';';
}

function transFerence(val) {
  var params = [];
  for (var key in val) {
    params.push(key + '=\'' + val[key] + '\'');
  }
  return params.join(',');
}

//更新信息查询像个人信息
function updatainfo(arr, phone) {
  return 'UPDATE appunion.`userInfo` SET ' + arr + ' WHERE phone =' + phone;
}


app.post('/user/mp3', function(req, res) {
  var json = req.body;
  // 语音合成，保存到本地文件
  clientbaidu.text2audio(json.tex, {spd: 5, per: json.num}).then(function(result) {
    if (result.data) {
      fs.stat('../Message-Board/music/mp3',function(error,stats){
        if(error){
          fs.mkdir('../Message-Board/music/mp3',function(error){
            console.log('创建目录成功');
          });
        }else{
          fs.rmdir('../Message-Board/music/mp3',function(error){
            console.log('删除目录成功');
            fs.mkdir('../Message-Board/music/mp3',function(error){
              console.log('创建目录成功');
            });
          })
        }
      })
      var name = '../Message-Board/music/mp3/tts' + new Date().getTime();
      fs.writeFileSync(name + '.mp3', result.data);
      res.send({data: 'tts' + new Date().getTime() + '.mp3'})
    } else {
      // 合成服务发生错误
      console.log('语音合成失败: ' + JSON.stringify(result));
    }
  }, function(err) {
    console.log(err);
  });
})
//登录
app.post('/user/login', function(req, res) {
  var json = req.body;
  // var sqla="SELECT * FROM test.`userInfo`";
  dbsql.query(inquiryinfo(json.username), function(error, results, fields) {
    try {
      if (results.length !== 0) {
        for (var i = 0; i < results.length; i++) {
          if (json.username !== results[i].phone || json.password !==
              results[i].password) {
            res.send({result: 403, data: {}, msg: '账号或者密码错误'});
            res.end();
          } else {
            res.send({result: 1, data: {}, msg: '成功'});
            res.end();
          }
        }
      } else {
        res.send({result: 403, data: {}, msg: '账号不存在'});
        res.end();
      }
    } catch (e) {
      res.send({result: 50000, data: {}, msg: '服务器异常'});
      res.end();
    }

  });
});
//注册
app.post('/user/register', function(req, res) {
  var json = req.body;
  var registerinfo = 'INSERT INTO appunion.`userInfo` (phone, password, groomcode) VALUES (' +
      json.phone + ' , ' + json.password + ', ' + json.groomcode + ');';
  dbsql.query(inquiryinfo(json.phone), function(error, results, fields) {
    try {
      if (results.length !== 0) {
        res.send({result: 0, data: {}, msg: '已注册'});
        res.end();
      } else {
        dbsql.query(registerinfo, function(error, results, fields) {
          if (error == null) {
            res.send({result: 1, data: {}, msg: '成功'});
            res.end();
          }
        });
      }
    } catch (e) {
      res.send({result: 50000, data: {}, msg: '服务器异常'});
      res.end();
    }
  });
});
//短信验证码
app.post('/user/getmessage', function(req, res) {
  var json = req.body;
  res.send({result: 1, data: 987654, msg: '成功'});
  // var sql="INSERT INTO userInfo VALUES (uid,'"+json.Name+"' , '"+json.pass+"');"
  // dbsql.query(sql, function (error, results, fields) {
  //   if (error==null) {
  //     res.send({result:1,data:{},msg:"成功"});
  //     res.end();
  //   }
  // });
});
//更新个人信息
app.post('/user/updateuserinfo', function(req, res) {
  var json = req.body;
  dbsql.query(updatainfo(transFerence(json), json.phone),
      function(error, results, fields) {
        console.log(error);
        try {
          if (error === null) {
            res.send({result: 1, data: null, msg: '保存成功'});
            res.end();
          } else {
            res.send({result: 0, data: null, msg: '保存失败'});
            res.end();
          }
        } catch (e) {
          res.send({result: 50000, data: {}, msg: '服务器异常'});
          res.end();
        }
      });
});
//获取个人信息
app.post('/user/getpersondata', function(req, res) {
  var json = req.body;
  dbsql.query(inquiryinfo(json.phone), function(error, results, fields) {
    try {
      if (results.length !== 0) {
        res.send({result: 0, data: results[0], msg: '查询成功'});
        res.end();
      } else {
        res.send({result: 0, data: {}, msg: '暂无'});
        res.end();
      }
    } catch (e) {
      res.send({result: 50000, data: {}, msg: '服务器异常'});
      res.end();
    }
  });
});

// 获取优品库
app.post('/mall/getcommodity', function(req, res) {
  var json = req.body;
  client.execute('taobao.tbk.uatm.favorites.get', {
    'page_no': '1',
    'page_size': '20',
    'fields': 'favorites_title,favorites_id,type',
    'type': '1',
  }, function(error, response) {
    try {
      client.execute('taobao.tbk.uatm.favorites.item.get', {
        'platform': '1',
        'page_size': json.pageSize,
        'adzone_id': 82941000008,
        'unid': '966',
        'favorites_id': response.results.tbk_favorites[json.subordinate]['favorites_id'],
        'page_no': '',
        'fields': 'coupon_click_url,coupon_end_time,coupon_info,coupon_start_time,coupon_total_count,num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick,shop_title,zk_final_price_wap,event_start_time,event_end_time,tk_rate,status,type',
      }, function(error, responsed) {
        try {
          res.send(responsed);
        } catch (e) {
          res.send({result: 50000, data: {}, msg: '服务器异常'});
          res.end();
        }
      });
    } catch (e) {
      res.send({result: 50000, data: {}, msg: '服务器异常'});
      res.end();
    }
  });
});
// 查询商品详情
app.post('/mall/getcommodityinfo', function(req, res) {
  var json = req.body;
  client.execute('taobao.tbk.item.info.get', {
    'num_iids': json.num_iids,
    'platform': '20',
    'ip': '',
  }, function(error, response) {
    try {
      res.send(response);
    } catch (e) {
      res.send({result: 50000, data: {}, msg: '服务器异常'});
      res.end();
    }
  });
});

// app.post('/user/uploadPhoto',function(req, res) {
//
// });
app.post('/user/uploadPhoto', function(req, res, next) {
  // res.send('1')
  var form = new formidable.IncomingForm();
  // 设置文件保存路径，相对路径
  form.uploadDir = './uploads';
  form.multiples = true;//设置为多文件上传
  form.keepExtensions = true;//是否包含文件后缀
  var filesd = [];
  var json = {};
  //文件都将保存在files数组中
  form.on('file', function(filed, file) {
    filesd.push(filed);
  });
  form.on('field', function(name, value) {
    json[name] = value;
  });
  form.parse(req, function(err, fields, files) {
    for (var k = 0; k < filesd.length; k++) {
      let fileSuffix= files[filesd[k]]['path'].substr(files[filesd[k]]['path'].lastIndexOf(".") + 1);
      var oldpath = files[filesd[k]]['path'];
      let stream = fs.createReadStream(oldpath);
      try {
        dbsql.query(inquiryinfo(json.phone), function(error, results, fields) {
          if (results.length !== 0) {
            let parms = {};
            putStream(stream, json.phone+'.' + fileSuffix).then(parms=>{
              dbsql.query(updatainfo(transFerence({
                imageurl: parms.url
              }),json.phone), function(error, results, fields) {
                if (error === null){
                  res.send({result: 0, data: {
                      imageurl: parms.url
                    }, msg: '成功'});
                  res.end();
                } else {
                  res.send({result: 1, data: {}, msg: '失败'});
                  res.end();
                }
              })
            });
          } else {
            res.send({result: 0, data: {}, msg: '暂无'});
            res.end();
          }
        });
        fs.unlink(oldpath,function(error){
          if(error){
            console.log(error);
            return false;
          }
        })
      }catch (e) {
        res.send({result: 50000, data: {}, msg: '服务器异常'});
        res.end();
      }
    }
  });
});
async function putStream (stream, phone) {
  try {
    // use 'chunked encoding'
    // console.log(stream)
    var urlnme = 'headCode' + phone;
    let result = {};
    await OSSclient.putStream('headCode/' + urlnme, stream).then(function(res) {
      result = res;
    });
    return result
  } catch (e) {
    res.send({result: 50000, data: {}, msg: '服务器异常'});
    res.end();
  }
}
